<template>
  <div class="app-container">
    <div class="config-title">虚拟数据配置</div>
    <div class="config-box">
      <div class="config-item" v-hasPermi="['system:weVirtualDataConfig:edit']">
        <div class="config-label">虚拟数据开关</div>
        <div class="config-value">
          <el-switch
            v-model="virtualData.configValue"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="true"
            inactive-value="false"
            active-text="开"
            inactive-text="关"
            @change="handleSwitch"
          />
          <el-button
            type="danger"
            plain
            icon="el-icon-refresh"
            size="mini"
            @click="handleRefreshCache"
            v-hasPermi="['system:weVirtualDataConfig:remove']"
          >
            刷新缓存
          </el-button>
          <div class="virtual-tip">切换虚拟数据开关后，需“刷新缓存”才会生效</div>
        </div>
      </div>
      <div class="config-item" v-hasPermi="['system:weVirtualData:template']">
        <div class="config-label">虚拟数据模板</div>
        <div class="config-value">
          <div class="w-b-b-a">{{ templateName }}</div>
          <el-button
            plain
            size="mini"
            type="primary"
            icon="el-icon-download"
            :disabled="!templateUrl"
            @click="importTemplate(templateUrl)"
          >
            下载
          </el-button>

          <div v-if="lastFileUrl" class="mt30 w-b-b-a">{{ lastFileName }}</div>
          <el-button
            v-if="lastFileUrl"
            plain
            size="mini"
            type="primary"
            icon="el-icon-download"
            @click="importTemplate(lastFileUrl)"
          >
            最近导入文件
          </el-button>
          <div class="virtual-tip">模板内容只需修改蓝色字体内容即可</div>
        </div>
      </div>
      <div class="config-item" v-hasPermi="['system:weVirtualData:import']">
        <div class="config-label">虚拟数据导入</div>
        <div class="config-value">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="headers"
            :action="actionUrl"
            :disabled="isUploading"
            :before-upload="handleBeforeUpload"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            auto-upload
            drag
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将虚拟数据模板拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
            </div>
          </el-upload>
        </div>
      </div>
    </div>
    <div v-hasPermi="['system:workshop_virtualData:query']" class="config-title">
      车间虚拟数据配置
    </div>
    <div class="config-box" v-hasPermi="['system:workshop_virtualData:query']">
      <div v-for="item in workshopList" :key="item.id" class="config-item">
        <div class="config-label">
          {{ item.remark }}
          <el-button
            round
            plain
            size="mini"
            type="primary"
            v-hasPermi="['system:workshop_virtualData:edit']"
            @click="editWorkshop(item)"
          >
            编辑
          </el-button>
        </div>
        <div class="config-value">
          <el-carousel indicator-position="none" style="width: 100%; margin-bottom: 0">
            <el-carousel-item v-for="(img, index) in item.imgs" :key="index">
              <img :src="img" style="width: 100%; height: 100%; object-fit: cover" />
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </div>

    <el-dialog
      :visible.sync="workshopShow"
      title="车间虚拟数据编辑"
      width="800"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="workshopRef"
        :model="workshopForm"
        :rules="workshopRules"
        label-width="100px"
      >
        <el-form-item label="车间名称" prop="remark">
          <el-input
            v-model="workshopForm.remark"
            placeholder="请输入车间名称"
            maxlength="20"
            clearable
          />
        </el-form-item>
        <el-form-item v-if="workshopForm.imgs" label="车间图片" prop="imgs">
          <div>
            <div v-if="workshopForm.imgs.length > 0" class="workshop-img">
              <div
                v-for="(url, index) in workshopForm.imgs"
                :key="index"
                class="img-item"
              >
                <el-image
                  :src="url"
                  lazy
                  fit="cover"
                  :preview-src-list="workshopForm.imgs"
                  style="width: 100%; height: 100%"
                />
                <i class="el-icon-error" @click="deleteImg(index)" />
              </div>
            </div>
            <el-upload
              ref="imgRef"
              :limit="4"
              accept=".jpg, .png, .jpeg, .gif"
              :headers="headers"
              :action="uploadImgUrl"
              :on-success="handleSuccess"
              auto-upload
              :style="{
                marginTop:
                  workshopForm.imgs && workshopForm.imgs.length > 0 ? '20px' : '0',
              }"
            >
              <el-button size="mini" type="primary"> 上传 </el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model="workshopForm.sort"
            type="number"
            placeholder="请输入车间排序"
          />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="submitWorkshop"> 保存 </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { listConfig } from "@/api/system/config";
import {
  updateVirtual,
  refreshCache,
  getWorkshopList,
  updateWorkshop,
  getVirtualTemplate,
} from "@/api/srceen/config";
export default {
  name: "virtualData",
  data() {
    return {
      virtualData: {},
      isUploading: false, // 是否禁用上传
      templateUrl: "", // 下载模板地址
      lastFileUrl: "", // 最后导入的文件地址
      headers: { Authorization: "Bearer " + getToken() }, // 设置上传的请求头部
      actionUrl: process.env.VUE_APP_BASE_API + "/screen/weVirtualData/importData",
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload",
      workshopList: [], // 车间列表
      workshopShow: false, // 车间弹窗
      workshopForm: {
        // 车间表单
        imgs: [],
      },
      workshopRules: {
        imgs: [{ required: true, message: "请上传车间图片", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getVirtualInfo();
    this.isAuth("system:weVirtualData:template", () => this.getTemplate());
    this.isAuth("system:workshop_virtualData:query", () => this.getWorkshopData());
  },
  computed: {
    templateName() {
      if (!this.templateUrl) return "加载中";
      return this.templateUrl.substring(this.templateUrl.lastIndexOf("/") + 1);
    },
    lastFileName() {
      if (!this.lastFileUrl) return "";
      return this.lastFileUrl.substring(this.lastFileUrl.lastIndexOf("/") + 1);
    },
  },
  methods: {
    /** 获取虚拟数据信息 */
    getVirtualInfo() {
      listConfig({ configKey: "sys.showVirtualData" }).then((res) => {
        this.virtualData = res.rows[0];
      });
    },
    // 文件上传前处理
    handleBeforeUpload(file) {
      if (file.name.length > 50) {
        this.$modal.msgError("文件名不能超过50个字符");
        this.$refs.upload.clearFiles();
        return false;
      } else {
        this.isUploading = true;
      }
      return true;
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.isUploading = false;
      this.$refs.upload.clearFiles();
      this.getTemplate();
      this.$alert(
        "<div style='overflow: auto; overflow-x: hidden; max-height: 70vh; padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
    },
    // 文件上传失败处理
    handleFileError() {
      this.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    /** 获取模板地址 */
    getTemplate() {
      getVirtualTemplate().then((res) => {
        if (res.data) {
          this.templateUrl = res.data.templateUrl;
          this.lastFileUrl = res.data.lastFileUrl;
        }
      });
    },
    /** 下载模板操作 */
    importTemplate(href) {
      let alick = document.createElement("a");
      alick.href = href;
      alick.click();
      alick.remove();
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
    /** 虚拟数据切换 */
    handleSwitch() {
      updateVirtual(this.virtualData).then((res) => {
        this.$modal.msgSuccess("修改成功");
      });
    },
    // 获取车间列表
    getWorkshopData() {
      getWorkshopList().then((res) => {
        let list = res.data;
        list.forEach((i) => {
          i.imgs = i.imgUrl ? i.imgUrl.split(",") : [];
        });
        this.workshopList = list;
      });
    },
    // 编辑车间
    editWorkshop(row) {
      this.workshopForm = JSON.parse(JSON.stringify(row));
      this.workshopShow = true;
    },
    // 上传成功
    handleSuccess(res) {
      if (res.code === 200) {
        this.workshopForm.imgs.push(res.data.url);
        this.$refs.imgRef.clearFiles();
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError(res.msg);
      }
    },
    // 删除图片
    deleteImg(index) {
      this.workshopForm.imgs.splice(index, 1);
    },
    // 保存车间数据
    submitWorkshop() {
      this.$refs.workshopRef.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, this.workshopForm);
          data.imgUrl = data.imgs.join(",");
          delete data.imgs;
          updateWorkshop(data).then((res) => {
            this.$modal.msgSuccess("修改成功");
            this.workshopShow = false;
            this.getWorkshopData();
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.config-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  margin-top: 20px;
  &:first-child {
    margin-top: 0;
  }
}
.config-box {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
  .config-item {
    border-radius: 4px;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.12);
    transition: all 0.3s;
    &:hover {
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.24);
    }
    .config-label {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      border-bottom: 1px solid #dadada;
      position: relative;
      button {
        position: absolute;
        right: 20px;
      }
    }
    .config-value {
      padding: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      > div {
        margin-bottom: 20px;
      }
    }
  }
}
.virtual-tip {
  margin-top: 20px;
  font-size: 12px;
  color: #606266;
}
.workshop-img {
  width: 100%;
  height: 108px;
  object-fit: cover;
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(4, 1fr);
  margin-bottom: 10px;
  .img-item {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: relative;
    i {
      position: absolute;
      right: -10px;
      top: -10px;
      font-size: 20px;
      color: #f00;
      background-color: #fff;
      border-radius: 50%;
      &:hover {
        cursor: pointer;
        color: #f56c6c;
      }
    }
  }
}
::v-deep .el-carousel__arrow {
  background-color: rgba(0, 119, 255, 0.1);
}
</style>
